<template>
    <div class="dashboard">
        <!-- 搜索区域 -->
        <div class="search-area">
            <!-- 抖音号下拉选择 -->
            <el-select
                    v-model="nickname"
                    placeholder="抖音号昵称"
                    clearable
                    filterable
                    class="search-item short-input"
            >
                <el-option
                        v-for="item in nicknameOptions"
                        :key="item"
                        :label="item"
                        :value="item"
                />
            </el-select>

            <!-- 筛选类型 -->
            <el-select v-model="filterType" placeholder="类型" class="short-select">
                <el-option label="日期" value="date"></el-option>
                <el-option label="月份" value="month"></el-option>
            </el-select>

            <!-- 日期选择 -->
            <div v-if="filterType === 'date'" class="search-item date-picker">
                <!-- 桌面端 -->
                <el-date-picker
                        v-if="!isMobile"
                        v-model="dateRange"
                        type="daterange"
                        start-placeholder="起始日期"
                        end-placeholder="结束日期"
                        format="YYYY-MM-DD"
                        teleported
                ></el-date-picker>

                <!-- 移动端 -->
                <div v-else class="mobile-date-range">
                    <el-date-picker
                            v-model="startDate"
                            type="date"
                            placeholder="起始日期"
                            format="YYYY-MM-DD"
                            teleported
                    ></el-date-picker>
                    <el-date-picker
                            v-model="endDate"
                            type="date"
                            placeholder="结束日期"
                            format="YYYY-MM-DD"
                            teleported
                    ></el-date-picker>
                </div>
            </div>

            <!-- 月份选择 -->
            <div v-else-if="filterType === 'month'" class="search-item date-picker">
                <!-- 桌面端 -->
                <el-date-picker
                        v-if="!isMobile"
                        v-model="monthRange"
                        type="monthrange"
                        start-placeholder="起始月份"
                        end-placeholder="结束月份"
                        format="YYYY-MM"
                        teleported
                ></el-date-picker>

                <!-- 移动端 -->
                <div v-else class="mobile-date-range">
                    <el-date-picker
                            v-model="startMonth"
                            type="month"
                            placeholder="起始月份"
                            format="YYYY-MM"
                            teleported
                    ></el-date-picker>
                    <el-date-picker
                            v-model="endMonth"
                            type="month"
                            placeholder="结束月份"
                            format="YYYY-MM"
                            teleported
                    ></el-date-picker>
                </div>
            </div>

            <!-- 搜索按钮 -->
            <el-button type="primary" @click="search" class="search-item btn-search">
                搜索
            </el-button>
        </div>

        <!-- 数据展示 -->
        <div v-if="Object.keys(groupedData).length > 0" class="board-wrapper">
            <div
                    v-for="(records, shopName) in groupedData"
                    :key="shopName"
                    class="shop-row"
            >

                <!-- 左侧店铺卡片 -->
                <div class="shop-name-card">
                    <div>
                        <span class="month-label">当月</span>
                    </div>
                    <div class="shop-info" style="padding-top: 20px">
                        <div style="size: 20px;font-weight: bold;">{{ shopName }}</div>
                        <div>GMV: {{ formatToWan(shopMonthData[shopName]?.sum_month_gmv || 0) }}</div>
                        <div>消耗: {{ formatToWan(shopMonthData[shopName]?.sum_month_cost || 0) }}</div>
                        <div>ROI: {{ shopMonthData[shopName]?.month_roi || 0 }}</div>
                    </div>

                </div>




                <div class="metric-card" v-for="metric in metrics" :key="metric.key">
                    <div class="metric-header">
                        <span>{{ metric.label }}</span>
                        <span class="metric-total">
              总计：<strong>{{ getMetricTotal(shopName, metric.key) }}</strong>
            </span>
                    </div>

                    <div class="metric-bar-container">
                        <div
                                v-for="record in records"
                                :key="record.anchor"
                                class="metric-bar-item"
                        >
                            <div class="anchor-label">{{ record.anchor }}</div>

                            <div
                                    class="bar"
                                    :style="{ width: getBarWidth(shopName, metric.key, record[metric.key]) + '%' }"
                            ></div>
                            <div class="bar-value">
                                {{
                                metric.key === "sum_live_mins"
                                ? record.sum_live_mins_ch
                                : formatToWan(record[metric.key])
                                }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 无数据提示 -->
        <div v-else class="no-data">
            <el-empty description="暂无数据，请调整筛选条件试试～"/>
        </div>
    </div>
</template>

<script setup>
    import {ref, computed, onMounted} from "vue";
    import {ElMessage} from "element-plus";
    import api from "../api";
    import dayjs from "dayjs";
    import {formatToWan} from '../utils/number.js'

    const nicknameOptions = [
        "anta kids潮流旗舰店",
        "Levi‘s李维斯童装集合店",
        "ROOKIE卖场店童装直播间",
        "ROOKIE官方旗舰店",
        "ROOKIE官方旗舰店直播号",
        "ROOKIE官旗书包号",
        "ROOKIE官旗童装号",
        "特步儿童户外旗舰店",
        "特步儿童户外运动直播间",
        "翼启飞童鞋专营店",
    ];

    const nickname = ref("");
    const filterType = ref("date");
    const dateRange = ref([]);
    const startDate = ref("");
    const endDate = ref("");
    const monthRange = ref([]);
    const startMonth = ref("");
    const endMonth = ref("");
    const groupedData = ref({});
    const shopMonthData = ref({});
    const isMobile = computed(() => window.innerWidth <= 768);

    onMounted(() => {
        const yesterday = dayjs().subtract(1, "day").format("YYYY-MM-DD");
        dateRange.value = [yesterday, yesterday];
        startDate.value = yesterday;
        endDate.value = yesterday;
        search();
    });

    const search = async () => {
        let star_parm = "";
        let end_parm = "";

        // ✅ 判空逻辑
        if (filterType.value === "date") {
            if (!isMobile.value) {
                if (!dateRange.value || dateRange.value.length < 2) {
                    ElMessage.warning("请选择起始日期和结束日期！");
                    return;
                }
                star_parm = dayjs(dateRange.value[0]).format("YYYY-MM-DD");
                end_parm = dayjs(dateRange.value[1]).format("YYYY-MM-DD");
            } else {
                if (!startDate.value || !endDate.value) {
                    ElMessage.warning("起始日期和结束日期不能为空！");
                    return;
                }
                star_parm = dayjs(startDate.value).format("YYYY-MM-DD");
                end_parm = dayjs(endDate.value).format("YYYY-MM-DD");
            }
        } else if (filterType.value === "month") {
            if (!isMobile.value) {
                if (!monthRange.value || monthRange.value.length < 2) {
                    ElMessage.warning("请选择起始月份和结束月份！");
                    return;
                }
                star_parm = dayjs(monthRange.value[0]).format("YYYY-MM");
                end_parm = dayjs(monthRange.value[1]).format("YYYY-MM");
            } else {
                if (!startMonth.value || !endMonth.value) {
                    ElMessage.warning("起始月份和结束月份不能为空！");
                    return;
                }
                star_parm = dayjs(startMonth.value).format("YYYY-MM");
                end_parm = dayjs(endMonth.value).format("YYYY-MM");
            }
        }

        const res = await api.post("/dashboard/datas", {
            nickname: nickname.value,
            date_or_month: filterType.value,
            star_parm,
            end_parm,
        });

        const shop_month_data_res = await api.post("/dashboard/shop_month_datas");
        console.log(shop_month_data_res.data);
        shopMonthData.value = shop_month_data_res.data
        groupedData.value = res.data;
    };

    const metrics = [
        {key: "sum_gmv", label: "GMV"},
        {key: "sum_cost", label: "消耗"},
        {key: "sum_actual_roi", label: "实际ROI"},
        {key: "sum_live_mins", label: "时长"},
    ];

    function getMetricTotal(shopName, key) {
        const records = groupedData.value[shopName];
        if (!records || !records.length) return "-";
        if (key === "sum_live_mins") {
            const totalMinutes = records.reduce(
                (sum, r) => sum + parseFloat(r.sum_live_mins || 0),
                0
            );
            return minutesToText(totalMinutes);
        } else if (key === "sum_actual_roi") {
            const totalGmv = records.reduce(
                (sum, r) => sum + parseFloat(r.sum_daily_gmv || 0),
                0
            );
            const totalOrderSubsidy = records.reduce(
                (sum, r) => sum + parseFloat(r.sum_order_subsidy || 0),
                0
            );

            const totalCost = records.reduce(
                (sum, r) => sum + parseFloat(r.sum_daily_cost || 0),
                0
            );
            const totalHangingFee = records.reduce(
                (sum, r) => sum + parseFloat(r.sum_hanging_fee || 0),
                0
            );
            if ((totalCost + totalHangingFee) > 0) {
                return formatToWan(((totalGmv - totalOrderSubsidy) / (totalCost + totalHangingFee)).toFixed(2));
            } else {
                return 0;
            }


        }
        const total = records.reduce((sum, r) => sum + parseFloat(r[key] || 0), 0);
        return formatToWan(total.toFixed(2));
    }

    function getBarWidth(shopName, key, value) {
        const records = groupedData.value[shopName];
        let total = 100;
        if (key != "sum_actual_roi") {
            total = records.reduce((sum, r) => sum + parseFloat(r[key] || 0), 0);
        }
        const num = parseFloat(value) || 0;
        const max = Math.ceil(total);
        if (key === "sum_actual_roi") {
            console.log(shopName + "bar:", (max > 0 ? Math.min((num / max) * 100, 100) : 0))
        }
        return max > 0 ? Math.min((num / max) * 100, 100) : 0;
    }

    function minutesToText(minutes) {
        const h = Math.floor(minutes / 60);
        const m = minutes % 60;
        return h > 0 ? `${h}小时${m}分钟` : `${m}分钟`;
    }

    function truncateName(str, maxLength = 5) {
        if (!str) return "";
        // 计算字符串长度（支持中英文混合）
        let len = 0;
        let result = "";
        for (const ch of str) {
            len += /[^\x00-\xff]/.test(ch) ? 1 : 0.5; // 中文算1，英文算0.5
            result += ch;
            if (len >= maxLength) {
                result += "...";
                break;
            }
        }
        return result;
    }


</script>

<style scoped>
    .dashboard {
        padding: 16px;
    }

    .search-area {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 10px;
        margin-bottom: 20px;
    }

    .short-input {
        width: 160px;
    }

    .short-select {
        width: 90px;
    }

    .date-picker .el-date-editor {
        width: 220px !important;
    }

    .btn-search {
        width: 80px;
    }

    /* 桌面端展示 */
    .board-wrapper {
        display: flex;
        flex-direction: column;
        gap: 20px;
        padding: 10px;
    }

    .shop-row {
        display: flex;
        align-items: stretch;
        gap: 10px;
    }


    .shop-name-card {
        flex: none;
        width: 220px;
        background: #f6f8ff;
        border: 1px solid #bcd3ff;
        border-radius: 8px;
        box-shadow: 0 2px 6px rgba(140, 160, 255, 0.2);
        padding: 10px 12px;
        display: flex;
        flex-direction: column;
        position: relative; /* ✅ 关键：让子元素可绝对定位 */
        box-sizing: border-box;
    }



    /* 店铺名字体最大、加粗 */
    .shop-title {
        font-size: 16px;
        font-weight: bold;
        color: #000000;
        line-height: 1.4;
        text-align: left;
        word-break: break-all;
    }

    /* 当月小标签：右上角、小两号、浅灰 */
    .month-label {
        position: absolute; /* 绝对定位 */
        top: 6px;           /* 距离上边6px */
        right: 8px;         /* 距离右边8px */
        font-size: 12px;    /* 小两号 */
        font-weight: bold;
        color: #000000;     /* 灰色字体 */
    }

    /* GMV、消耗、ROI：靠左、小一号 */
    .shop-info {
        font-size: 14px;
        color: #000000;
        display: flex;
        flex-direction: column;
        gap: 4px;
        text-align: left;
        line-height: 2;
    }


    .metric-card {
        flex: 1;
        background: #edf4ff;
        border-radius: 10px;
        border: 1px solid #bcd3ff;
        padding: 10px;
        box-shadow: 1px 1px 4px rgba(100, 150, 255, 0.15);
        box-sizing: border-box;
    }

    .metric-header {
        display: flex;
        justify-content: space-between;
        font-weight: bold;
        font-size: 14px;
        color: #000000;
        border-bottom: 1px solid #c7dafc;
        margin-bottom: 6px;
        padding-bottom: 4px;
    }

    .metric-bar-item {
        display: flex;
        align-items: center;
        gap: 6px;
        margin-bottom: 10px;
    }

    .bar {
        height: 23px;
        background: #3471ea;
        /*border-radius: 9px;*/
        transition: all 0.3s ease;
    }

    .bar:hover {
        background: #3471ea;
        transform: scaleY(1.1);

    }

    .bar-value {
        width: 80px;
        text-align: right;
        font-size: 13px;
        color: #000000;
    }

    .anchor-label {
        width: 70px; /* 可调，适配你文字长度 */
        text-align: left;
        font-size: 13px;
        color: #000000;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        flex-shrink: 0; /* 防止被压缩 */
    }

    .shop-title {
        font-weight: bold;
        font-size: 16px;
        text-align: center;
        margin-bottom: 10px;
        color: #000;
    }



    /* ✅ 移动端优化 */
    @media (max-width: 768px) {
        .search-area {
            flex-direction: column;
            align-items: stretch;
            gap: 12px;
        }

        .search-item,
        .short-input,
        .short-select,
        .date-picker .el-date-editor,
        .btn-search {
            width: 100% !important;
            box-sizing: border-box;
        }

        /* 上下结构的日期/月选择器 */
        .mobile-date-range {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .mobile-date-range .el-date-editor {
            width: 100% !important;
        }

        .shop-row {
            flex-direction: column;
            align-items: stretch;
        }

        .metric-card {
            width: 100%;
            max-width: 100%;
            box-sizing: border-box;
        }

        .bar {
            height: 12px;
            /*border-radius: 6px;*/
        }

        .board-wrapper {
            padding: 4px;
        }

        .anchor-label {
            width: 60px; /* ✅ 固定宽度，可自行调整 */
            display: inline-block; /* 让宽度生效 */
            white-space: nowrap; /* 不换行 */
            overflow: hidden; /* 隐藏超出部分 */
            text-overflow: ellipsis; /* 超出显示省略号 */
            font-size: 13px;
            color: #000000;
            text-align: left;

        }

        .shop-name-card {
            width: 100%;
            padding: 10px;
        }

        .shop-title {
            font-size: 15px;
        }

        .shop-info {
            font-size: 13px;
        }

        .month-label {
            top: 5px;
            right: 10px;
            font-size: 11px;
        }
    }

    /* 日期面板不被遮挡、居中 */
    :deep(.el-picker-panel) {
        z-index: 9999 !important;
    }
</style>
